/*
* Call includes for the message and constants file
*/
includes Custom;
includes Constants;

module BaseMoteM {
  provides {
    interface StdControl;
  }
  uses {
    interface Leds;
    interface StdControl as CommControl;
    interface SendMsg as Send;
	interface ReceiveMsg as Recv;
	interface Timer;
  }
}
implementation {
    struct TOS_Msg sendData;
	struct CustomMsg *message;
	
  /**
   * Initialize variables and other interfaces
   **/
  command result_t StdControl.init() {
    call Leds.init();
    call CommControl.init();
	message = (struct CustomMsg *)sendData.data;
    return SUCCESS;
  }


  /**
   * Start the comm control
   **/
  command result_t StdControl.start() {
    call CommControl.start();
	call Timer.start(TIMER_REPEAT, 20000);
    return SUCCESS;
  }

  
  /**
   * Halt execution of the application.
   **/
  command result_t StdControl.stop() {
    call CommControl.stop();
	call Timer.stop();
    return SUCCESS;
  }
  
  /**
  * This seems weird but to show up in the program the Beacon MUST send some data so we
  * Send it to ourself every 20 seconds. It isn't any sort of useful information
  **/
  task void sendTask()
  {
    atomic {

		message-> source = 0x00;
		message-> destination = 0x00;
		message-> cost = 0x00;
		message-> msgtype = 0x00;
		message-> pos_x = 0x00;
		message-> pos_y = 0x00;
    }
	
    call Send.send(0, sizeof(struct CustomMsg), &sendData);
  }
  
 /**
  * Send the data everytime the timer fires
  **/
  event result_t Timer.fired()
  {
    //Leds are simply for debugging
	call Leds.redToggle();
    post sendTask();
	return SUCCESS;
  }

  

  
  
  /**
   * Event handler for the sendDone event.
   * Required because this module uses the SendMsg interface.
   **/
  event result_t Send.sendDone(TOS_MsgPtr msg, result_t success)
  {
    return SUCCESS;
  }


  
  event TOS_MsgPtr Recv.receive(TOS_MsgPtr m)
  {
	//Convert the message to our custom type
	CustomMsg *rMsg = (CustomMsg *)m->data;
	
	//Make sure the destination was the base station and it isn't an admin message
	if(rMsg->destination == 0x00 && rMsg->msgtype != ADMIN_MSG)
	{
		//Toggle all the lights to show we received something!
		call Leds.redToggle();
		call Leds.greenToggle();
		call Leds.yellowToggle();
	}
	
	return m;
  }
  
}


